package com.kerpow.KSheet;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

public class CompendiumParser extends DefaultHandler {

	private String _currentTag;
	private String _targetPower;
	private String _currentID;
	
	public String getPowerID(String xml, String powerName){
		_targetPower = powerName;
		try {
	        /* Create a URL we want to load some xml-data from. */
			
			/* Get a SAXParser from the SAXPArserFactory. */
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			
			/* Get the XMLReader of the SAXParser we created. */
			XMLReader xr = sp.getXMLReader();
			/* Create a new ContentHandler and apply it to the XML-Reader*/
			
			//ExampleHandler myExampleHandler = new ExampleHandler();
		    xr.setContentHandler(this);
		   
		    /* Parse the xml-data from our URL. */
			
			InputStream is = new ByteArrayInputStream( xml.getBytes() );
			xr.parse(new InputSource(is));
			/* Parsing has finished. */
			
			/* Our ExampleHandler now provides the parsed data to us. */
			//ParsedExampleDataSet parsedExampleDataSet = myExampleHandler.getParsedData();
			
			/* Set the result to be displayed in our GUI. */
			//tv.setText(parsedExampleDataSet.toString());
		} catch (Exception e) {
			//Log.i("kerpow","SAX: " + e.toString());
		}
		
		return _currentID;
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {

		super.characters(ch, start, length);
		
		String value = new String(ch, start, length);
		if(_currentTag.equals("ID")) 
			_currentID = value;
		if(_currentTag.equals("Name") &&  value.equals(_targetPower) ){
			throw new SAXException("ID Found");
		}
		
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		_currentTag = "";
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {

		super.startElement(uri, localName, qName, attributes);
		_currentTag = localName;
	}
	
}
